const app = getApp()

Page({
  data: {
    showKeyboard: true,
    isInput:false,
    is_get_coupon:false,
    store_id: 0,
    chain_id: 0,
    input_money:'',    //基础价
    discount_money: 0, //已优惠多少钱
    amount: 0, //付款金额
    coupon_user: [],  //客户赠品礼包
    coupon_user_id: 0,
    coupon_user_key: 0,
  },
  onLoad: function (options) {
    app.getParam(options,(param) => {
      this.data.store_id = app.util().isNull(param.store_id) ? 0 : param.store_id
      this.data.chain_id = app.util().isNull(param.chain_id) ? 0 : param.chain_id
    })    
  },
  onShow:function(){
    this.setData({
      disabled:false
    })
    app.isLogin((rel) =>{
      if(rel){
        this.getCoupon();
      }
    })
  },
  //读取用户已领赠品
  getCoupon: function () {
    app.api().Get('api/v1/smartbc/storepay/index',{store_id:this.data.store_id,chain_id:this.data.chain_id},(rel) => {
      if(rel.code == 200){
        console.log(rel.data.store);
        this.setData({
          store: rel.data.store,
          coupon_user:rel.data.coupon,
          is_get_coupon:rel.data.is_get_coupon
        })
      }
    });
    this.amount();
  },
  //选择已有赠品
  selectCouponUser: function (event) {
    if (this.data.input_money <= 0) {
      app.wxAlert('请输入付款金额');
      return;
    }
    var coupon_user_key = event.currentTarget.dataset.key;
    var coupon_user  = this.data.coupon_user
    var coupon_user_id = event.currentTarget.dataset.id;
    if(coupon_user[coupon_user_key].is_end == 1){
      return;
    }
    if(this.data.coupon_user_id == coupon_user_id){
      this.resestApi(); //相同就徐晓选择
      return;
    }else{
      this.setData({
        coupon_user_id:event.currentTarget.dataset.id,
      })
      this.data.coupon_user_key = event.currentTarget.dataset.key
      this.amount() //计算价格
    }
  },
  //价格计算方式
  amount:function () {
    var coupon_user  = this.data.coupon_user,coupon_user_key = this.data.coupon_user_key;
    var discount_money = 0; //已优惠有价格
    if (this.data.coupon_user_id){
      if (coupon_user[coupon_user_key].types == 1) {
        var discount = parseFloat(coupon_user[coupon_user_key].discount) / 10;   //折扣比例
        discount_money = this.data.input_money - this.data.input_money * discount;  //优惠了多少钱
      } else {
        discount_money = parseFloat(coupon_user[coupon_user_key].price);
      }
    }
    //判断优惠后价格禁止小于0
    if (parseFloat(this.data.input_money) <= 0) {
      this.setData({
        input_money: 0
      })
    }
    var amount = parseFloat(this.data.input_money - discount_money);
    if (amount <= 0) {
      amount = 0;
    }
    this.setData({
      discount_money: discount_money.toFixed(2),
      amount: amount.toFixed(2),
    })
  },
  /**
   * 提交付款中
   */
  doSubmitPay:function () {
    if (this.data.input_money == 0){
      app.wxAlert('请输入付款金额');
    }else{
      if (this.data.coupon_user.length > 0 && this.data.coupon_user_id == 0) {
        wx.showModal({
          content:'你还有赠品未使用？',
          cancelText:'不使用',confirmText	:'去使用',
          success:(res) => {
            if (res.cancel) {
              this.getCouponPayment();
            }
          }
        })
      }else{
        this.getCouponPayment();
      }
    }
  },
  /**
   * 判断是否需要获取优惠卷
   * 如果是新用户就先领取一个再付款
   */
  getCouponPayment: function () {
    if(this.data.is_get_coupon == true){
      app.api().Post('api/v1/smartbc/coupon/getCoupon',{id:this.data.coupon_user_id},(rel) => {
        this.wechatPayment(rel.data.id)
      })
    }else{
      this.wechatPayment(this.data.coupon_user_id)
    }
  },
  //微信
  wechatPayment: function (coupon_user_id) {
    this.setData({
      disabled:true
    })
    app.api().Post('api/v1/smartbc/storepay/wechat',{
      store_id:this.data.store_id,
      chain_id:this.data.chain_id,
      user_couponr_id:coupon_user_id,
      money:this.data.input_money,
      amount:this.data.amount
    },(result) => {
      if(result.code == 200){
        app.doWechatPay(result.data,(rel) => {
          this.setData({disabled:false})
          wx.redirectTo({
            url:'coupon?store_id='+this.data.store_id
          })
        },() => {
          this.setData({disabled:false})
          app.wxAlert('支付失败');
        });
      }else{
        this.setData({disabled:false})
        app.wxAlert(result.msg);
      }
    })
  },
  
  //不用赠品
  resestApi() {
    this.setData({
      coupon_user_id: 0,
      discount_money: 0,
    });
    this.data.coupon_user_key = 0;
    this.amount() //计算价格
  },
  //键盘是否显示
  showKeyboard() {
    this.setData({
      showKeyboard:!this.data.showKeyboard,
    });
    if(this.data.showKeyboard == false){
      this.resestApi();
      this.onCoupon();
    }
  },
  //判断优惠券是否运行选择和锁定
  onCoupon() {
    var coupon_user  = this.data.coupon_user,input_money = this.data.input_money;
    for (let i in coupon_user) {
      coupon_user[i].is_end = input_money < coupon_user[i].howmuch ? 1:0;
    }
    this.setData({
      coupon_user: coupon_user,
    });
  },
  //虚拟键盘输入
  onKeyboard(event) {
    var keys = event.detail.keyboard,input_money = this.data.input_money.toString(),len = input_money.length;
    switch (keys) {
      case '.':
        if (len < 11 && input_money.indexOf('.') == -1) {
          if (input_money.length < 1) {
            input_money = '0.';
          } else {
            input_money += '.';
          }
        }
        break;
      case 'backspace':
        input_money = input_money.substr(0,input_money.length - 1);
        break;
    default:
      let Index = input_money.indexOf('.');
      if (Index == -1 || len - Index != 3) {
        if (len < 11) {
          input_money += keys;
        }
      }
      break
    }
    this.setData({
      input_money:input_money,
      isInput:input_money ? true : false,
    });
  }
})